package com.jcnet.bizaia.fragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jcnet.bizaia.App;
import com.jcnet.bizaia.MyJCDownloadActivity;
import com.jcnet.bizaia.R;
import com.jcnet.bizaia.VideoViewPlayingActivity;
import com.jcnet.bizaia.bean.DownloadBean;
import com.jcnet.bizaia.bean.SeVoiceList;
import com.jcnet.bizaia.bean.VoiceDetailBean;
import com.jcnet.bizaia.service.JCMusicPlayerService;
import com.jcnet.bizaia.service.JCMusicPlayerService.LocalBinder;
import com.mozillaonline.providers.DownloadManager;
import com.squareup.picasso.Picasso;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

@SuppressLint("ValidFragment")
public class DownLoadFragment extends Fragment implements OnItemClickListener{


	private DownloadManager mDownloadManager;
	private Cursor mDateSortedCursor;
	private Cursor mSizeSortedCursor;

	private Cursor myCursor;

	private ListView listView;


	private int mStatusColumnId;
	private int mIdColumnId;
	private int mLocalUriColumnId;
	private int mMediaTypeColumnId;
	private int mReasonColumndId;


	private List<DownloadBean> beans;

	private MyAdapter myAdapter;

	private int type = 1;
	

	private BroadcastReceiver broadcastReceiver;
	
	private boolean isbind  = false;
	
	//List<VoiceDetailBean> mainInfoBeans = new ArrayList<VoiceDetailBean>();
	SeVoiceList seVoiceList ;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = View.inflate(getActivity(), R.layout.comm_simple_list_base, null);
		listView = (ListView)view.findViewById(R.id.commSimpleListViewBase);
		listView.setOnItemClickListener(this);
		return view;
	}

	public DownLoadFragment(int type) {
		super();
		this.type = type;
	}




	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		


		// TODO Auto-generated method stub

		beans = new ArrayList<DownloadBean>();

		mDownloadManager = new DownloadManager(getActivity().getContentResolver(),
				getActivity().getPackageName());
		mDownloadManager.setAccessAllDownloads(true);

		DownloadManager.Query baseQuery = new DownloadManager.Query()
		.setOnlyIncludeVisibleInDownloadsUi(true);

		DownloadManager.Query myqQuery = new DownloadManager.Query().setFilterByStatus(8);


		mDateSortedCursor = mDownloadManager.query(baseQuery);


		mSizeSortedCursor = mDownloadManager.query(baseQuery.orderBy(
				DownloadManager.COLUMN_TOTAL_SIZE_BYTES,
				DownloadManager.Query.ORDER_DESCENDING));

		myCursor = mDownloadManager.query(myqQuery);

		myAdapter = new MyAdapter(beans);

		seVoiceList = new SeVoiceList() ;

		setData();

		listView.setAdapter(myAdapter);


		broadcastReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub
				setData();
				listView.setAdapter(new MyAdapter(beans));
				System.out.println("下载有新情况亲 注意查看列表 ....");
			}
		};

		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
		//intentFilter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);

		getActivity().registerReceiver(broadcastReceiver, intentFilter);
	}


	
	private void setData() {
		// TODO Auto-generated method stub
		beans.clear();
		while (myCursor.moveToNext()) {

			if((myCursor.getString(myCursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE)).startsWith("audio"))&&type==2){
				DownloadBean downloadBean = 	new DownloadBean(
						"",
						myCursor.getString(myCursor.getColumnIndex(DownloadManager.COLUMN_ID)), 
						myCursor.getString(myCursor.getColumnIndex(DownloadManager.COLUMN_TITLE)),
						myCursor.getString(myCursor.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP)), 
						myCursor.getString(myCursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE)), 
						myCursor.getString(myCursor.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION)), 
						myCursor.getString(myCursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
				beans.add(downloadBean);
				
				for (DownloadBean bean : beans) {
					seVoiceList.getMainInfoBeans().add(new VoiceDetailBean(Integer.parseInt(bean.getID()), bean.getTitle(), bean.getDescription(), bean.getDate(), "", bean.getPlayURL()));
				}
			}
			if((myCursor.getString(myCursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE)).startsWith("video"))&&type==1){
				DownloadBean downloadBean = 	new DownloadBean(
						"",
						myCursor.getString(myCursor.getColumnIndex(DownloadManager.COLUMN_ID)), 
						myCursor.getString(myCursor.getColumnIndex(DownloadManager.COLUMN_TITLE)),
						myCursor.getString(myCursor.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP)), 
						myCursor.getString(myCursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE)), 
						myCursor.getString(myCursor.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION)), 
						myCursor.getString(myCursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
				beans.add(downloadBean);
			}
		}
		myCursor.close();
	}



	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		getActivity().unregisterReceiver(broadcastReceiver);
	}

	class MyAdapter extends BaseAdapter{

		public int count;

		List<DownloadBean>beanx;

		public MyAdapter(List<DownloadBean>beanx) {
			super();
			this.beanx = beanx;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			count = beanx.size();
			return count;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder;
			if(convertView == null)
			{
				holder = new ViewHolder();
				convertView = View.inflate(getActivity(),R.layout.comm_list_info, null);
				holder.imageView = (ImageView)convertView.findViewById(R.id.imageView) ;
				holder.titleTextView = (TextView)convertView.findViewById(R.id.title);
				holder.subTitleTextView = (TextView)convertView.findViewById(R.id.subTitle);
				holder.imgIconImageView = (ImageView)convertView.findViewById(R.id.icon);

				convertView.setTag(holder);
			}else
			{
				holder = (ViewHolder)convertView.getTag();

			}

			DownloadBean infoBean  =   beans.get(position);
			if(infoBean!=null){

				holder.titleTextView.setText(infoBean.getTitle());
				holder.subTitleTextView.setText(new Date(Long.parseLong(infoBean.getDate()))+"\n\r"+infoBean.getType());
				// aQuery.id(holder.imageView).image(App.HTTP_PATH+infoBean.getPictureurl(), options);
				Picasso.with(getActivity())
				.load(App.HTTP_PATH+infoBean.getImg())
				.resize(80, 60)
				.centerCrop()
				.into(holder.imageView);
			}
			return convertView;
		}


		class ViewHolder {
			ImageView imageView;
			TextView subTitleTextView;
			TextView titleTextView;
			ImageView imgIconImageView;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		

		// TODO Auto-generated method stub
		if(type==1){
			Intent intent =new Intent(getActivity(),VideoViewPlayingActivity.class);
			intent.putExtra("URL", beans.get(position).getPlayURL());
			startActivity(intent);
		}
		if(type==2){
			
			Intent intent = new Intent(MyJCDownloadActivity.PLAY_LOCAL_MUSIC);
			App.seVoiceList = seVoiceList;
			intent.putExtra("pos", position);
			getActivity().sendBroadcast(intent);
		}
		
	}
}
